﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MvcCarConsume.Domain.Entites;

namespace MvcCarConsume.Domain
{
    public class SqlStatictcs : IStatictics
    {
        private string connStr;
        public SqlStatictcs(string connectionString)
        {
            connStr = connectionString;
        }

        public bool AddHistory(string ipAddress,  string url, string urlReferrer, DateTime time, string culture)
        {
            using (MvcCarDBEntities db = new MvcCarDBEntities(connStr))
            {
                try
                {
                    var newrecord = new statistics_history
                    {
                        IPAddress = ipAddress,
                        Url = url,
                        UrlReferrer = urlReferrer,
                        Time = time,
                        Culture = culture
                    };
                    db.statistics_history.AddObject(newrecord);
                    db.SaveChanges();
                    return true;
                }
                catch { return false; }
            }
        }

        public bool AddAction(string controllerName, string actionName)
        {
            using (MvcCarDBEntities db = new MvcCarDBEntities(connStr))
            {
                try
                {
                    var prerecord = db.statictics_actioncount.FirstOrDefault(p => (p.Controller == controllerName && p.Action == actionName));
                    if (prerecord != null)
                    {
                        prerecord.Count += 1;
                        db.SaveChanges();
                    }
                    else
                    {
                        var newrecord = new statictics_actioncount{
                            Controller = controllerName,
                            Action = actionName,
                            Count = 1
                        };
                        db.statictics_actioncount.AddObject(newrecord);
                        db.SaveChanges();
                    }
                    return true;
                }
                catch { return false; }
            }
        }
    }
}
